/*
 * Copyright (C) 2025 ameise <ameise.wang@gmail.com> - All Rights Reserved
 *
 * This file is part of e3pool.
 *
 * e3pool is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * e3pool is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with e3pool. If not, see <https://www.gnu.org/licenses/>.
 */

package go_pool

import "sync"

type taskResult struct {
	result any
	err    error
}

type task struct {
	syncChan chan<- taskResult
	f        any
	args     []any
}

var taskPool sync.Pool

func init() {
	taskPool = sync.Pool{
		New: func() any {
			return &task{
				syncChan: nil,
			}
		},
	}
}

func newTask(ch chan<- taskResult, f any, args []any) *task {
	t := taskPool.Get().(*task)
	t.syncChan = ch
	t.f = f
	t.args = args
	return t
}

func freeTask(t *task) {
	t.syncChan = nil
	t.f = nil
	t.args = nil
	taskPool.Put(t)
}

func doTask(t *task) {
	switch f := t.f.(type) {
	case GoSyncFunc:
		var r taskResult
		r.result, r.err = f(t.args...)
		t.syncChan <- r
	case GoAsyncFunc:
		f(t.args...)
		freeTask(t)
	default:
		panic("invalid task func type")
	}
}

func doTaskSafe(h PanicHook, where string, t *task) {
	switch f := t.f.(type) {
	case GoSyncFunc:
		var r taskResult
		r.err = ErrDoTaskPanic
		safeFunc(h, where, func(...any) {
			r.result, r.err = f(t.args...)
		})
		t.syncChan <- r
	case GoAsyncFunc:
		safeFunc(h, where, func(...any) {
			f(t.args...)
		})
		freeTask(t) //异步的任务,所有权由执行者管理
	default:
		panic("invalid task func type")
	}
}
